package oa.hleast.xswl.service;

import lombok.AllArgsConstructor;
import oa.hleast.common.constant.AuthConstant;
import oa.hleast.common.web.exception.BizException;
import oa.hleast.common.web.util.RequestUtils;
import oa.hleast.xswl.pojo.domain.User;
import oa.hleast.xswl.pojo.dto.AuthMemberDTO;
import oa.hleast.xswl.pojo.dto.UserDTO;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * 自定义用户认证和授权
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private ISysUserService sysUserService;
    private IUmsUserService umsUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String clientId = RequestUtils.getAuthClientId();

        User user = null;
        switch (clientId) {
            case AuthConstant.ADMIN_CLIENT_ID:
                // 后台用户
                UserDTO userDTO = sysUserService.getUserByUsername(username);
                userDTO.setClientId(clientId);
                user = new User(userDTO);
                break;
            case AuthConstant.MP_CLIENT_ID:
                // 小程序会员
                AuthMemberDTO authMemberDTO = umsUserService.getUserByOpenid(username);
                authMemberDTO.setClientId(clientId);
                user = new User(authMemberDTO);
                break;
            case AuthConstant.MP_CLIENT_CITY_BRAIN_APP:
                // 城市大脑会员
                AuthMemberDTO cityBrainMemberDTO = umsUserService.getUserByCustUserId(username);
                cityBrainMemberDTO.setClientId(clientId);
                user = new User(cityBrainMemberDTO);
                break;
            case AuthConstant.MP_ZJFWW_APP:
            case AuthConstant.MP_ZJFWW_WLYY_APP:
                // 浙里办-文旅红 and 浙里办-文旅预约
                AuthMemberDTO wlhMemberDTO = umsUserService.getUserByZjfwwUserId(username);
                wlhMemberDTO.setClientId(clientId);
                user = new User(wlhMemberDTO);
                break;
            default:
                throw new BizException("没有对应的用户");
        }
        if (!user.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        } else if (!user.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定!");
        } else if (!user.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期!");
        }
        return user;
    }

}
